package com.aceitunaproject.server.entity;

import java.awt.Point;
import java.util.HashMap;
import java.util.Iterator;
import java.util.Map;

import com.aceitunaproject.server.player.Player;

import com.sun.sgs.app.AppContext;
import com.sun.sgs.app.DataManager;
import com.sun.sgs.app.ManagedReference;

/**
 * 
 * Abstract class containing the functionality common to all entities that have
 * people on them (Unit,Settlement)
 * 
 * @author Federico Bergstein (Frodo)
 * 
 */
public abstract class PeopleContainer extends BasicEntity {

	private static final long serialVersionUID = 1L;

	private Map<String,ManagedReference<Loyalty>> loyalties = new HashMap<String, ManagedReference<Loyalty>>();
	private long persons = 0;
	
	/**
	 * Morale represents the strength of will and cohesion of the people in the unit/settlement 
	 */
	private double morale;
	
	public PeopleContainer(Long id, String name, Player owner, Player controller,double morale,long l,Loyalty[] loyalties,Point position) {
		super(id, name, owner, controller,position);
		DataManager dm = AppContext.getDataManager();
		
		for (int i = 0; i < loyalties.length; i++) {
			this.loyalties.put(loyalties[i].getPlayer().getName(), dm.createReference(new Loyalty(loyalties[i].getPlayer())));
		}
		this.persons = l;
		this.morale = morale;
	}
	
	/**
	 * Gets the set of Loyalties the Entity has
	 * @return the set of Loyalties
	 */
	public Loyalty[] getLoyalties() {
		Loyalty[] retLoyalties = new Loyalty[loyalties.size()];
		
		Iterator<ManagedReference<Loyalty>> iter =  loyalties.values().iterator();
		
		for (int i = 0; i < loyalties.size(); i++) {
			retLoyalties[i] = iter.next().get();
		}
		return retLoyalties;
	}
	
	/**
	 * Gets the Loyalty matching the given player
	 * @param player the player to match with a Loyalty
	 * @return the Loyalty matching the given player
	 */
	public Loyalty GetLoyalty(Player player) {
		return loyalties.get(player.getName()).get();
	}
	
	/**
	 * Gets the level of morale
	 * 
	 * @return the level of morale
	 */
	public double getMorale() {
		return morale;
	}
	
	/**
	 * Sets the level of morale
	 * 
	 * @param the level of morale
	 */
	public void setMorale(double morale) {
		AppContext.getDataManager().markForUpdate(this);
		this.morale = morale;
	}

	/**
	 * Sets the number of persons contained by this entity
	 * @param l the number of persons to set
	 */
	public void setPersons(long l) {
		AppContext.getDataManager().markForUpdate(this);
		this.persons = l;
	}

	/**
	 * Gets the number of persons contained by this entity
	 * @return the number persons
	 */
	public long getPersons() {
		return persons;
	}

}
